package net.gz01.wallet.web.controller.admin;

import com.alibaba.druid.util.StringUtils;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.upload.UploadFile;
import net.gz01.util.ZODate;
import net.gz01.util.ZOFile;
import net.gz01.util.ZOLog;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.config.SystemEnum;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.HeTongConfig;

import java.io.File;

public class HeTongController extends BaseController {
    public void search(){
        render("basedata/hetongList.html");
    }

    public void listJson(){
        ZOSearchCondition sc = super.getSearchCondition();
        Page<HeTongConfig> pageResult = HeTongConfig.dao.search(sc);
        renderJson(new PageRespon(pageResult));
    }

    public void  addPage(){
        render("basedata/hetongAdd.html");
    }

    @Before(Tx.class)
    public void batchHetong(){
        UploadFile upload = getFile();
        String title = getPara("title");
        String keyword = getPara("keyword");

        if(StringUtils.isEmpty(title)){
            renderFail("合同标题不能为空");
            return;
        }

        if(StringUtils.isEmpty(keyword)){
            renderFail("合同关键字不能为空");
            return;
        }

        ZOLog.api.info("收到数据:" + upload.getFileName() + "," + title + "," + keyword);
        HeTongConfig heTongConfig = new HeTongConfig();
        heTongConfig.setSignKeyword(keyword);
        heTongConfig.setTitle(title);
        heTongConfig.setFilename(upload.getFileName());

        String merchDataPath = SystemEnum.FilePath.PDF.getValue();
        ZOFile.mkdir(merchDataPath);
        heTongConfig.setPdfUrl(ZOIDGenerate.getUUID()+".pdf");
        String serverName = merchDataPath + heTongConfig.getPdfUrl();
        heTongConfig.setUpdateTime(ZODate.getDateTime());

        //处理文件
       {
           upload.getFile().renameTo(new File(serverName));
           upload.getFile().delete();
        }

        heTongConfig.save();
        renderSuccess();

    }


    public void  updatePage(){
        String id = getPara("id");
        HeTongConfig heTongConfig = HeTongConfig.dao.selectById(id);

        boolean ff = heTongConfig.getEnable();
        heTongConfig.setEnable(!ff);
        heTongConfig.update();

        renderSuccess("修改成功!");

    }

    public void look(){
        String id = getPara("id");
        HeTongConfig heTongConfig = HeTongConfig.dao.selectById(id);
        redirect(SystemConfig.config.get("myUrl") + heTongConfig.getPdfUrl());
    }


}
